#include<iostream>
#include<vector>
using namespace std;


class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int curGas = 0;
        int startPos = 0;
        for (int i = 0; i < gas.size(); i++) {
            curGas += gas[i];
            curGas = curGas - cost[i];
            if (curGas < 0) {
                curGas = 0;
                startPos = i + 1;
            }
        }
        for (int i = 0; i < startPos; i++) {
            curGas += gas[i];
            curGas = curGas - cost[i];
            if (curGas < 0) {
                return -1;
            }
        }
        return startPos;
    }
};